package cn.uo86.bs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import cn.uo86.bs.filebrowser.FileExplorerActivity;
import cn.uo86.bs.utils.Utils;

public class DownFileActivity extends Activity implements OnClickListener{

	private static final boolean DEBUG = true;
	private static final String TAG = "DownFileActivity";
	private static final int REFRESH_UI = 100;
	private static final int DOWNFILE = 101;

	private Handler myHandler = new MyHandler();

	
	EditText fileName;
	EditText filePath;
	Button btn_Down;
	Button btn_ChoosePosition;
	ProgressBar pb;
	
	String downUrl;
	long	totalSize;
	
	public static int REQUEST_CODE = 518;
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.downfile);
		init();
		
		downUrl = getIntent().getStringExtra("URL");
		totalSize = getIntent().getLongExtra("TOTALSIZE", 0);
		if(downUrl == null && totalSize ==0 ){
			finish();
		}
		
	}
	private void init() {
		fileName = (EditText)this.findViewById(R.id.filename);
		filePath = (EditText)this.findViewById(R.id.filepath);
		btn_Down = (Button) this.findViewById(R.id.btn_down);
		btn_ChoosePosition = (Button) this.findViewById(R.id.btn_chooseposition);
		btn_Down.setOnClickListener(this);
		btn_ChoosePosition.setOnClickListener(this);
		pb = (ProgressBar) this.findViewById(R.id.progressBar1);
		pb.setMax(100);
		pb.setProgress(0);
	}
	class MyHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			if (DEBUG)
				Utils.logi(TAG, "Message what=" + msg.what);
			switch (msg.what) {
			case REFRESH_UI:
				pb.setProgress(msg.arg1 * 100);
				break;
			case DOWNFILE:
						download(downUrl,filePath.getText().toString(),fileName.getText().toString(),totalSize);
				break;
			}
		}
	}

	private void download(String downUrl, String filePath,
			String fileName,long totalSize) {
		try {
			HttpURLConnection conn = null;
			int mTimeout = 3000;
			conn = (HttpURLConnection) new URL(downUrl).openConnection();
			conn.setDoInput(true);
			conn.setConnectTimeout(mTimeout);
			conn.setReadTimeout(mTimeout);
			conn.setRequestMethod("GET");
			int httpResponseCode = conn.getResponseCode();
			if (httpResponseCode == HttpURLConnection.HTTP_OK) {
				conn.connect();
				if(filePath.equals("")){
					filePath = "/mnt/sdcard";
				}
				File f = new File(filePath+"/"+fileName+".txt");
				if(!f.exists()){
					System.out.print(f.getAbsolutePath());
					f.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(f);
				InputStream is = conn.getInputStream();
				byte[] buf = new byte[2048];
				int len = 0;
				int temp = 0;
				while((len = is.read(buf))!= -1){
					fos.write(buf, 0, len);
					temp +=len;
					Message msg = new Message();
					msg.what = REFRESH_UI;
					if(temp !=0){
						msg.arg1 = (int) (totalSize/temp);
						myHandler.sendMessage(msg);
					}
				}
				Toast.makeText(DownFileActivity.this.getBaseContext(), "下载成功.", Toast.LENGTH_SHORT).show();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_CANCELED){
			return;
		}
		if(requestCode == REQUEST_CODE){
			String file_Path = data.getStringExtra("DIRECTORY_PATH");
			Log.v(TAG, file_Path);
			filePath.setText(file_Path);
		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_chooseposition:
			Intent intent = new Intent(getBaseContext(),FileExplorerActivity.class);
			startActivityForResult(intent, REQUEST_CODE);
			break;
		case R.id.btn_down:
			if(!fileName.getText().equals("")){
				myHandler.sendEmptyMessage(DOWNFILE);
			}else{
				Toast.makeText(getBaseContext(), "请输入有效文件名!", Toast.LENGTH_SHORT).show();
			}
			break;
		}
		
	}

}
